
function oneYearAgo(date) {
  const lastYear = new Date(date.setFullYear(date.getFullYear() - 1));
  return lastYear;
}

function formatToDate(date) {
  date = new Date(date - 24 * 60 * 60 * 1000)
  const month = date.getMonth() + 1; // getMonth()返回0-11，因此需要+1
  const day = date.getDate();
  const year = date.getFullYear();

  const formattedMonth = month < 10 ? `0${month}` : month;
  const formattedDay = day < 10 ? `0${day}` : day;

  return `${formattedMonth}/${formattedDay}/${year}`;
}

let isRequestInProgress = false;

function run() {
  if (isRequestInProgress) {
    return;
  }
  
  isRequestInProgress = true;
  showOverlay();
  
  const entityId = new URLSearchParams(location.search).get('entityId');
  const startDate = formatToDate(oneYearAgo(new Date()));
  const endDate = formatToDate(new Date());
  const url = `https://${location.host}/billing/transactions/getinvoicejson?entityId=${entityId}&startDate=${startDate}&endDate=${endDate}&pageStr=1&pageSizeStr=10&isPaid=true`;

  fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(async data => {
      const maxInvoiceId = data.invoiceList[0].invoiceId;
      const invoiceKey = maxInvoiceId.split('-')[0];
      const maxInvoiceIdNum = parseInt(maxInvoiceId.split('-')[1]);
      const baseURL = `https://${location.host}/sauron/billing/detail?entityId=${entityId}&invoiceId=${invoiceKey}-`;

      await updateMaxInvoiceIdNum(invoiceKey, maxInvoiceIdNum);
      chrome.runtime.sendMessage({ action: 'openUrlAndExecScript', data: { invoiceKey, maxInvoiceIdNum, baseURL } });
      isRequestInProgress = false;
    })
    .catch(error => {
      isRequestInProgress = false;
      setTimeout(run, 10000);
    });
}

async function updateMaxInvoiceIdNum(invoiceKey, maxInvoiceIdNum) {
  const uploadUrl = 'https://api.miraazzurra.com/amazon/ad/update_max_invoice_id_num';
  let retryTime = 0;
  while (retryTime < 3) {
    try {
      await post(uploadUrl, { invoiceKey, maxInvoiceIdNum });
      retryTime = 4; // 成功后退出循环
    } catch (error) {
      retryTime++;
      if (retryTime >= 3) {
        console.log('update max invoice id num失败')
        throw error
      }
    }
  }
}


run()

